<?php
// +----------------------------------------------------------------------
// | 高德地图
// +----------------------------------------------------------------------
namespace helper\ali;

use helper\facade\IMap;

class Map implements IMap
{
    private string $host = 'http://restapi.amap.com/v3';

    private string $key;

    public function __construct($config)
    {
        $this->key = $config['key'];
    }

    /**
     * 根据地址 获取经纬度
     * @param string $address
     * @return array
     */
    public function getLocation(string $address): array
    {
        $url = $this->host . '/geocode/geo?address=' . $address . '&key=' . $this->key;
        $result = $this->request('GET', $url);
        if ($result['statusCode'] == 200 && isset($result['body']['status']) && $result['body']['status'] == 1) {
            return $result['body']['geocodes'][0];
        } else {
            return [];
        }
    }

    /**
     * 根据经纬度 获取地址
     * @param $location string 116.481488,39.990464
     * @param string $batch
     * @return array
     */
    public function getAddress(string $location, string $batch = 'false'): array
    {
        $url = $this->host . "/geocode/regeo?output=json&location=$location&key=$this->key&batch=$batch";
        $result = $this->request('GET', $url);
        if ($result['statusCode'] == 200 && isset($result['body']['status']) && $result['body']['status'] == 1) {
            return $result['body']['regeocode'] ?? $result['body']['regeocodes'];
        } else {
            return [];
        }
    }

    /**
     * IP定位
     * @param $ip string
     * @return array
     */
    public function getIp($ip = '')
    {
        $parameters = $ip ? "&ip=$ip" : '';
        $url = $this->host . "/ip?key=$this->key" . $parameters;
        $result = $this->request('GET', $url);
        if ($result['statusCode'] == 200 && isset($result['body']['status']) && $result['body']['status'] == 1) {
            return $result['body'];
        } else {
            return [];
        }
    }

    /**
     * 行政区划获取
     * 1.国家统计局
     * 2.百度地图,高德地图,腾讯地图
     * 根据高德地图获取区划
     * 行政区名称、行政区代码
     * @param $keywords
     * @return array
     */
    public function district($keywords = '')
    {
        $url = $this->host . "/config/district?keywords={$keywords}&subdistrict=3&key={$this->key}";
        $result = $this->request('GET', $url);
        if ($result['statusCode'] == 200 && isset($result['body']['status']) && $result['body']['status'] == 1) {
            return $result['body'];
        } else {
            return [];
        }
    }

    /**
     * 关键词输入提升
     * @param string $region  城市
     * @param string $keyword 关键词
     * @return mixed
     */
    public function getSuggestion(string $region, string $keyword)
    {
        $url = $this->host . "/assistant/inputtips?key=$this->key&keywords=$keyword&city=$region&citylimit=true";
        $result = $this->request('GET', $url);
        if ($result['statusCode'] == 200 && isset($result['body']['status']) && $result['body']['status'] == 1) {
            return $result['body']['tips'];
        } else {
            return [];
        }
    }

    /**
     * 距离测量
     */
    public function distance($lat1, $lng1, $lat2, $lng2)
    {
        $url = $this->host . "/distance?origins=$lat1,$lng1&destination=$lat2,$lng2&output=json&key={$this->key}";
        $result = $this->request('GET', $url);
        if ($result['statusCode'] == 200 && isset($result['body']['status']) && $result['body']['status'] == 1) {
            return $result['body'];
        } else {
            return [];
        }
    }

    /**
     * 电动车路线规划
     */
    public function direction()
    {
        $url = "https://restapi.amap.com/v5/direction/electrobike";
        $result = $this->request('GET', $url);
        if ($result['statusCode'] == 200 && isset($result['body']['status']) && $result['body']['status'] == 1) {
            return $result['body'];
        } else {
            return [];
        }
    }

    /**
     * 发起请求 string $method, $uri = '', array $options = []
     * @param string $method
     * @param string $url
     * @param array  $options
     * @return array
     */
    private function request(string $method, string $url, array $options = [])
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        if (isset($options['headers'])) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $options['headers']);
        }
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $url, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        if (isset($options['json'])) {
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($options['json']));
        }

        $result      = curl_exec($curl);
        $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $rheader     = substr($result, 0, $header_size);
        $rbody       = substr($result, $header_size);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        return [
            'statusCode' => $httpCode,
            'body'       => json_decode($rbody, true)
        ];
    }
}
